package com.power.web.action.department;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.power.Constants;
import com.power.model.department.TiDepartment;
import com.power.model.hospital.TiHospital;
import com.power.model.member.TmMember;
import com.power.model.user.TsSysuser;
import com.power.services.department.DepartmentService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.FileUtil;
import com.power.util.PingYinUtil;
import com.power.util.RequestUtil;
import com.power.util.XmlUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TiDepartmentAction extends AbstractBaseAction {

	@Autowired
	@Qualifier("departmentService")
	private DepartmentService departmentService;

	private TiDepartment department;
	private String jsonString;
	private int flag;
    private File videoFile;
    private String videoFileFileName;
    
	@SuppressWarnings("unchecked")
	public String buildJSONString() {
		try {
			int start = this.start;
			int limit = this.limit;
			if (limit == 0)
				limit = 20;
			String departmentName = CharacterUtil.encode(RequestUtil.getParam(
					request, "departmentName", ""));
			Integer hid = RequestUtil.getParam(request, "hid", -1);
			Map<String, Object> map = this.departmentService.findAll(
					departmentName, start, limit, hid);
			List<Object[]> datalist = (List<Object[]>) map.get("data");
			List list = new ArrayList();
			for (Object[] obj : datalist) {
				TiDepartment ts = (TiDepartment) obj[0];
				TiHospital ti = (TiHospital) obj[1];
				ts.setHospitalName(ti.getName());
				list.add(ts);
			}
			int count = new Integer(map.get("count").toString());
			StringBuffer _JSONStr = null;
			String callback = this.callback;
			_JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("({\"total\":").append(count)
					.append(",\"results\":");
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor("inputDate",
					new DateJsonValueProcessor("yyyy-MM-dd kk:mm:ss"));
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			JSONArray jsonObject = JSONArray.fromObject(list, cfg);
			_JSONStr.append(jsonObject.toString());
			_JSONStr.append("})");
			jsonString = _JSONStr.toString();
		} catch (Exception e) {
			log.error("加载医院信息列表出错", e);
			this.jsonString = "[]";
		}
		return Constants.JSONSTRING_RESULT_NAME;
	}

	@SuppressWarnings("unchecked")
	public String loadByHospital() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<TiDepartment> list = new ArrayList<TiDepartment>();
		try {
			out = response.getWriter();
			Integer hid = RequestUtil.getParam(request, "hid", -1);
			if (hid != -1) {
				Map<String, Object> map = this.departmentService.findComboxAll("",
						start, limit, hid);
				list = (List<TiDepartment>) map.get("data");
			}
			String callback = RequestUtil.getParam(this.request, "callback",
					"callback");
			StringBuffer _JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("([");
			for (int i = 0; i < list.size(); ++i) {
				TiDepartment obj = (TiDepartment) list.get(i);
				_JSONStr.append("[\"").append(obj.getId()).append("\",");
				_JSONStr.append("\"").append(obj.getName()).append("\"],");
			}
			if (list.size() > 0)
				_JSONStr.deleteCharAt(_JSONStr.lastIndexOf(","));
			_JSONStr.append("])");
			this.jsonString = _JSONStr.toString();
			out.print(this.jsonString);
		} catch (Exception e) {
			log.error("加载单位出错", e);
			out.print("[]");
		}
		return null;
	}

	public String delete() throws Exception {
		String id = RequestUtil.getParam(this.request, "deleteID", "");
		String[] ids = id.split("_");
		try {
			this.response.setCharacterEncoding("UTF-8");
			for (int i = 0; i < ids.length; i++) {
				TiDepartment department = this.departmentService
						.read(new Integer(ids[i]));
				this.departmentService.delete(department);
			}
			this.response.getWriter().print("{success:true,msg:'删除成功!'}");
		} catch (Exception e) {
			log.error("输出JSON数据错误！", e);
			this.response.getWriter().print("{failure:true,msg:'删除失败!'}");
		}
		return null;
	}

	public String saveOrUpdate() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		try {
			if (null != department) {
			    if (null != videoFile) {
			        String   basePath = request.getSession().getServletContext()
                            .getRealPath("/");
			        String   compressPath = XmlUtil.getValue("imgPath",
                            "sysConfig")
                            + "/";
			        String   fileName = new Date().getTime()
                            + videoFileFileName.substring(videoFileFileName
                                    .lastIndexOf("."));
                    if (FileUtil.doUpFile(basePath + compressPath + fileName,
                        videoFile)) {
                        department.setVideosrc(compressPath + fileName);
                    }
                }
			    
			    
				TsSysuser user = (TsSysuser) this.session
						.get(Constants.USERINFO_KEY);
				department.setInputDate(DateTimeUtil.getCurrentDateTime());
				department.setInputMan(user.getUsername());
				department.setInputManId(user.getId());
				departmentService.saveOrUpdate(department);
			}
			this.response.getWriter().print("{success:true,msg:'保存成功!'}");
		} catch (Exception e) {
			log.error("科室信息保存失败", e);
			try {
				this.response.getWriter().print("{success:false,msg:'保存失败!'}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String save() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		if (null != department) {
		    if (null != videoFile) {
                String   basePath = request.getSession().getServletContext()
                        .getRealPath("/");
                String   compressPath = XmlUtil.getValue("imgPath",
                        "sysConfig")
                        + "/";
                String   fileName = new Date().getTime()
                        + videoFileFileName.substring(videoFileFileName
                                .lastIndexOf("."));
                if (FileUtil.doUpFile(basePath + compressPath + fileName,
                    videoFile)) {
                    department.setVideosrc(compressPath + fileName);
                }
            }
		    
			TsSysuser user = (TsSysuser) this.session
					.get(Constants.USERINFO_KEY);
			department.setInputDate(DateTimeUtil.getCurrentDateTime());
			department.setInputMan(user.getUsername());
			department.setInputManId(user.getId());
			department.setFullChar(PingYinUtil.getPingYin(department.getName(),
					1, 1));
			department.setFirstChar(PingYinUtil.getPingYin(
					department.getName(), 2, 1).substring(0, 1));
		}
		try {
			departmentService.saveOrUpdate(department);
			request.setAttribute("ifsuccess", "保存成功!");
		} catch (RuntimeException e) {
			request.setAttribute("ifsuccess", "保存失败!");
			e.printStackTrace();
		}
		return "ifsuccess";
	}

	public String showPage() {
		Integer hid = RequestUtil.getParam(request, "hid", 0);
		Integer did = RequestUtil.getParam(request, "did", 0);
		try {
			if (did == 0) {
				department = new TiDepartment();
				department.setDeleteFlag("0");
				department.setHid(hid);
			} else {
				department = departmentService.read(did);
			}
		} catch (Exception e) {
			log.error("获取数据错误");
			e.printStackTrace();
		}
		return "showPage";
	}

	public String read() {
		int id = RequestUtil.getParam(this.request, "id", -1);
		department = this.departmentService.read(new Integer(id));
		return "showdepartment";
	}

	public String execute() {
		return null;
	}

	public TiDepartment getdepartment() {
		return department;
	}

	public void setdepartment(TiDepartment department) {
		this.department = department;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public TiDepartment getDepartment() {
		return department;
	}

	public void setDepartment(TiDepartment department) {
		this.department = department;
	}

    public File getVideoFile() {
        return videoFile;
    }

    public void setVideoFile(File videoFile) {
        this.videoFile = videoFile;
    }

    public String getVideoFileFileName() {
        return videoFileFileName;
    }

    public void setVideoFileFileName(String videoFileFileName) {
        this.videoFileFileName = videoFileFileName;
    }

}